package com.flydust.apipulse.controller;

import com.flydust.apipulse.entity.Directory;
import com.flydust.apipulse.service.DirectoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

@RestController
@RequestMapping("/api/directories")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
public class DirectoryController {

    private static final Logger logger = Logger.getLogger(DirectoryController.class.getName());

    @Autowired
    private DirectoryService directoryService;

    // 获取所有目录
    @GetMapping
    public ResponseEntity<List<Directory>> getAllDirectories() {
        logger.info("获取所有目录列表");
        try {
            List<Directory> directories = directoryService.findAll();
            return ResponseEntity.ok(directories);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "获取目录列表时发生异常", e);
            throw e;
        }
    }

    // 根据项目ID获取目录
    @GetMapping("/project/{projectId}")
    public ResponseEntity<List<Directory>> getDirectoriesByProjectId(@PathVariable Long projectId) {
        logger.info("根据项目ID获取目录列表: " + projectId);
        try {
            List<Directory> directories = directoryService.findByProjectId(projectId);
            return ResponseEntity.ok(directories);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "根据项目ID获取目录列表时发生异常，项目ID: " + projectId, e);
            throw e;
        }
    }

    // 根据ID获取目录
    @GetMapping("/{id}")
    public ResponseEntity<Directory> getDirectoryById(@PathVariable Long id) {
        logger.info("根据ID获取目录: " + id);
        try {
            Optional<Directory> directory = directoryService.findById(id);
            if (directory.isPresent()) {
                return ResponseEntity.ok(directory.get());
            } else {
                logger.warning("未找到ID为 " + id + " 的目录");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "获取目录详情时发生异常，目录ID: " + id, e);
            throw e;
        }
    }

    // 创建目录
    @PostMapping
    public ResponseEntity<Directory> createDirectory(@RequestBody Directory directory) {
        logger.info("创建目录: " + directory.getName());
        try {
            Directory savedDirectory = directoryService.save(directory);
            return ResponseEntity.ok(savedDirectory);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "创建目录时发生异常，目录名称: " + directory.getName(), e);
            throw e;
        }
    }

    // 更新目录
    @PutMapping("/{id}")
    public ResponseEntity<Directory> updateDirectory(@PathVariable Long id, @RequestBody Directory directoryDetails) {
        logger.info("更新目录: " + id);
        try {
            Optional<Directory> directory = directoryService.findById(id);
            if (directory.isPresent()) {
                Directory updatedDirectory = directory.get();
                updatedDirectory.setName(directoryDetails.getName());
                Directory savedDirectory = directoryService.save(updatedDirectory);
                return ResponseEntity.ok(savedDirectory);
            } else {
                logger.warning("未找到ID为 " + id + " 的目录进行更新");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "更新目录时发生异常，目录ID: " + id, e);
            throw e;
        }
    }

    // 删除目录
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDirectory(@PathVariable Long id) {
        logger.info("删除目录: " + id);
        try {
            Optional<Directory> directory = directoryService.findById(id);
            if (directory.isPresent()) {
                directoryService.deleteById(id);
                return ResponseEntity.noContent().build();
            } else {
                logger.warning("未找到ID为 " + id + " 的目录进行删除");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "删除目录时发生异常，目录ID: " + id, e);
            throw e;
        }
    }
}